# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from ElevatorAdmin.settings import RESCUE_KEY, RESCUE_DATA_TYPE, RESCUE_INFO
from utils.views import WdAPIView, AuthenticationExceptView, WdListAPIView, WdRetrieveUpdateAPIView
from rest_framework.views import APIView
from utils.response import general_json_response, ErrorCode
from rest_framework import status
from utils.logger import get_logger
from basic.models import ElevatorInfo, ElevatorPersonInfo
from users.models import CompanyWebsiteInfo, CompanyInfo, Person, PersonPositions
from .models import RescueTask
from maintenance.models import Task
import json
from django.http.response import JsonResponse, HttpResponse
import requests
import re
import datetime
import time
from .serializer import RescueTaskListSerializer, RescueTaskRetrieveSerializer, RescueTaskSerializer
from manufacturer.models import ElevatorStatus, ElevatorWarning, AuthorityCode
import string
import random
from ElevatorAdmin.tasks import push_by_alias


logger = get_logger(__name__)


# def get_response(response):
#     response['Access-Control-Allow-Origin'] = '*'
#     return response


class HelloWorldView(AuthenticationExceptView, WdAPIView):

    def get(self, request, *args, **kwargs):
        return HttpResponse("hello world")


# 获取所有维保人员位置信息
class PersonPositionsView(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        now = datetime.datetime.now()
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2000100" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        res = {
            "LinsData": {
                "key": key,
                "dataType": 3,
                "operationCommand": "2000101",
                "msg": "success",
                "code": "0",
                "createDateTime": now.strftime("%Y-%m-%d %H:%M:%S"),
                "accuracyValue": "300",
                "dataList": []
                        }
                }
        positions = PersonPositions.objects.filter(is_new=True)
        company_ids = positions.values_list('service_id', flat=True).distinct()
        # company_ids = [185, 183]
        # l = [274, 275, 268, 261, 92, 90, 89, 87, 86, 406, 91, 88]
        for company_id in company_ids:
            persons = []
            sub_positions = positions.filter(service_id=company_id)
            for position in sub_positions:
                person = position.person
                persons.append({
                    "personnelID": str(person.id),
                    "personnelName": person.auth_user.real_name,
                    "markerCoordinates": position.position,
                })
            res['LinsData']['dataList'].append({
                "maintenanceID": str(company_id),
                "maintenanceName": CompanyInfo.objects.get(id=company_id).name,
                "person": persons
            })

        return JsonResponse(res)


# 根据电梯注册号查询维保商信息
class QueryCompanyByCodeView(AuthenticationExceptView, WdAPIView):
    """ 根据电梯注册号查询维保商信息"""

    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'deviceID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100200" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        code = data.get('deviceID', None)
        if not code:
            res['LinsData']['msg'] = u"电梯注册号缺失"
            return JsonResponse(res)
        # elevator = ElevatorInfo.objects.filter_active(register_code=code).first()
        elevator = ElevatorInfo.objects.filter_active(register_code=code).first()
        if not elevator:
            res['LinsData']['msg'] = u"电梯不存在，请检查"
            return JsonResponse(res)
        company = elevator.maintain_company
        company_webinfo = CompanyWebsiteInfo.objects.filter_active(company=company).first()
        res['LinsData'] = {
                        "key": key,
                        "dataType": RESCUE_DATA_TYPE,
                        "operationCommand": "2100201",
                        "gUID": g_uid,
                        "deviceID": code,
                        "dataList": [{
                            "maintenanceID": str(company.id),
                            "maintenanceName": company.name,
                            "legalPerson": company.legal_person,
                            "legalPhone": company.legal_phone,
                            "maintenanceTelephone": company_webinfo.emergency_phone,
                            "maintenanceLinkman": company.person_in_charge,
                            "maintenancePhone": company.person_in_charge_phone,
                            "officeMainPerson": company_webinfo.office_main_person,
                            "officeMainPhone": company_webinfo.office_main_person_phone,
                            "streetName": company_webinfo.office_address
                                        }],
                        "code": 0,
                        "msg": "success"
                        }
        return JsonResponse(res)


# 根据id查询维保商信息
class QueryCompanyByIDView(AuthenticationExceptView, WdAPIView):
    """ 根据id查询维保商信息"""

    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'maintenanceID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100202" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        code = data.get('maintenanceID', None)
        if not code:
            res['LinsData']['msg'] = u"维保商ID缺失"
            return JsonResponse(res)
        try:
            company_id = int(code)
        except Exception as e:
            res['LinsData']['msg'] = u"维保商ID有误"
            logger.info(e)
            return JsonResponse(res)
        company = CompanyInfo.objects.filter_active(company_type=100, id=company_id).first()
        # company = CompanyInfo.objects.filter_active(company_type=100, id=company_id).filter(id__in=[183, 185]).first()
        if not company:
            res['LinsData']['msg'] = u"维保商不存在"
            return JsonResponse(res)
        company_webinfo = CompanyWebsiteInfo.objects.filter_active(company=company).first()
        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100203",
            "gUID": g_uid,
            "maintenanceID": code,
            "dataList": [{
                "maintenanceID": str(company.id),
                "maintenanceName": company.name,
                "legalPerson": company.legal_person,
                "legalPhone": company.legal_phone,
                "maintenanceTelephone": company_webinfo.emergency_phone,
                "maintenanceLinkman": company.person_in_charge,
                "maintenancePhone": company.person_in_charge_phone,
                "officeMainPerson": company_webinfo.office_main_person,
                "officeMainPhone": company_webinfo.office_main_person_phone,
                "streetName": company_webinfo.office_address
            }],
            "code": 0,
            "msg": "success"
        }
        # response = JsonResponse(res)
        # response = get_response(response)
        return JsonResponse(res)


# 查询所有维保商信息
class QueryAllCompanyIdView(AuthenticationExceptView, WdAPIView):
    """ 查询所有维保商信息"""

    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100204" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        # companys = CompanyInfo.objects.filter_active(company_type=100)
        companys = CompanyInfo.objects.filter_active(company_type=100)
        ids = [str(company.id) for company in companys]
        ids = " ".join(ids)

        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100205",
            "gUID": g_uid,
            "maintenanceID": ids,
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 根据电梯注册号查询救援人员信息
class QueryPersonByCodeView(AuthenticationExceptView, WdAPIView):
    """ 根据电梯注册号查询救援人员信息"""

    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
            print keys
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'deviceID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100300" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        code = data.get('deviceID', None)
        if not code:
            res['LinsData']['msg'] = u"电梯注册号缺失"
            return JsonResponse(res)
        # elevator = ElevatorInfo.objects.filter_active(register_code=code).first()
        # elevator = ElevatorInfo.objects.filter_active(register_code=code, service_id__in=[183, 185]).first()
        elevator = ElevatorInfo.objects.filter_active(register_code=code).first()
        if not elevator:
            res['LinsData']['msg'] = u"电梯不存在，请检查"
            return JsonResponse(res)
        company = elevator.maintain_company
        ep = ElevatorPersonInfo.objects.filter(elevator=elevator, worker_type=20, status=10)
        data_list = []
        for e in ep:
            dic = {
                "maintenanceID": str(company.id),
                "maintenanceName": company.name,
                "personnelID": str(e.worker.id),
                "personnelName": e.worker.auth_user.real_name,
                "identityCard": e.worker.card_id,
                "mobileTelephone": e.worker.auth_user.phone
            }
            data_list.append(dic)

        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100301",
            "gUID": g_uid,
            "dataList": data_list,
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 根据救援人员ID获取信息
class QueryPersonByIdView(AuthenticationExceptView, WdAPIView):
    """
    根据救援人员ID获取信息
    """
    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'personnelID']
        if sorted(keys) != sorted(key_format):
            print "++++++++++++"
            print sorted(keys)
            print sorted(key_format)
            print bool(sorted(keys) == sorted(key_format))
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        personnel_id = data.get('personnelID', None)
        personnel_id = int(personnel_id)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100302" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        if not personnel_id:
            res['LinsData']['msg'] = u'救援人员ID缺失'
            return JsonResponse(res)
        # rescuer_person_obj = Person.objects.filter_active(id=personnel_id).first()
        # rescuer_person_obj = Person.objects.filter_active(id=personnel_id, service_id__in=[183, 185]).first()
        rescuer_person_obj = Person.objects.filter_active(id=personnel_id).first()
        if not rescuer_person_obj:
            res['LinsData']['msg'] = u"未找到该救援人员, 请检查"
            return JsonResponse(res)
        data_list = []
        company_id = rescuer_person_obj.company.id
        company_name = rescuer_person_obj.company.name
        personnel_name = rescuer_person_obj.auth_user.real_name
        identity_card = rescuer_person_obj.card_id
        mobile_phone = rescuer_person_obj.auth_user.phone
        dic = {
            "maintenanceID": str(company_id),
            "maintenanceName": company_name,
            "personnelID": str(personnel_id),
            "personnelName": personnel_name,
            "identityCard": identity_card,
            "mobileTelephone": mobile_phone
        }
        data_list.append(dic)
        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100303",
            "gUID": g_uid,
            "dataList": data_list,
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 根据维保公司ID获取其所有的救援人员id
class QueryAllPersonByCompanyView(AuthenticationExceptView, WdAPIView):
    """
    根据维保公司ID获取其所有的救援人员id
    """
    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'maintenanceID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        company_id = data.get('maintenanceID', None)
        company_id = int(company_id)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100304" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        if not company_id:
            res['LinsData']['msg'] = u'维保商ID缺失,请检查'
            return JsonResponse(res)
        # company_obj = CompanyInfo.objects.filter_active(id=company_id, company_type=100).first()
        # company_obj = CompanyInfo.objects.filter_active(id=company_id, company_type=100).filter(id__in=[183, 185]).first()
        company_obj = CompanyInfo.objects.filter_active(id=company_id, company_type=100).first()
        if not company_obj:
            res['LinsData']['msg'] = u'该维保商不存在，请检查'
            return JsonResponse(res)
        company_id = company_obj.id
        workers = ElevatorPersonInfo.objects.filter(service_id=company_id, worker_type=20, status=10).\
            values_list('worker', flat=True).distinct()
        personnel_ids = [str(worker) for worker in workers]
        personnel_ids = " ".join(personnel_ids)
        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100305",
            "gUID": g_uid,
            "personnelID": personnel_ids,
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 根据电梯注册码获取电梯的基本信息
class QueryElevatorInfoByCodeView(AuthenticationExceptView, WdAPIView):
    """
    根据电梯注册码获取电梯的基本信息
    """

    def post(self, request, *args, **kwargs):
        global elevator_type_name
        global layer_amount
        global station_amount
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'deviceID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        code = data.get('deviceID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100400" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        if not code:
            res['LinsData']['msg'] = u"电梯注册号缺失"
            return JsonResponse(res)
        elevator_obj = ElevatorInfo.objects.filter_active(register_code=code).first()
        # elevator_obj = ElevatorInfo.objects.filter_active(register_code=code).filter(service_id__in=[183, 185]).first()
        if not elevator_obj:
            res['LinsData']['msg'] = u"电梯不存在，请检查"
            return JsonResponse(res)

        # 获取电梯类型名称
        elevator_type = elevator_obj.elevator_type
        if elevator_type == 10:
            elevator_type_name = u"曳引与强制驱动电梯"
        elif elevator_type == 20:
            elevator_type_name = u"液压驱动电梯"
        elif elevator_type == 30:
            elevator_type_name = u"杂物电梯"
        elif elevator_type == 40:
            elevator_type_name = u"自动扶梯"

        # 获取电梯制造厂商
        product_company_name = elevator_obj.product_company

        # 获取电梯的层站
        stations = elevator_obj.stations
        if stations:
            stations = stations.strip()
            if "/" in stations:
                layer_amount = stations.split('/')[0]
                station_amount = stations.split('/')[1]
            elif "层" in stations:
                stations_lis = re.findall(r"\d+", stations)
                layer_amount = stations_lis[0]
                station_amount = stations_lis[1]
        else:
            layer_amount = None
            station_amount = None

        # 获取维保单位电话
        maintain_company_id = elevator_obj.maintain_company.id if elevator_obj.maintain_company else None
        website_obj = CompanyWebsiteInfo.objects.filter_active(company=maintain_company_id).first() if maintain_company_id else None
        maintenance_telephone = website_obj.emergency_phone if website_obj else None


        # 获取使用单位的电话
        owner_telephone = elevator_obj.property_company.company_telephone
        if owner_telephone:
            owner_telephone = owner_telephone
        else:
            owner_telephone = ''


        #
        # # 通过百度地图api获取电梯地理位置
        # items = {'location': elevator_coordinates, 'ak': 'C8eNlnlZ0qNHhx22eFU5aBWuiGhGCWI6', 'output': 'json'}
        # res = requests.get('http://api.map.baidu.com/geocoder/v2/', params=items)
        # position_data = res.json()
        # position_data = position_data.get("result")
        # street_name = position_data.get("formatted_address")

        data_list = []
        if elevator_obj.next_yearly_inspection_date:
            l = elevator_obj.next_yearly_inspection_date.strftime("%Y-%m").split("-")
            nextYearlyInspectionDate = l[0] + "年" + l[1].lstrip("0") + "月"
        else:
            nextYearlyInspectionDate = ""
        nowTime = datetime.datetime.now()
        tt = datetime.datetime(year=nowTime.year, month=nowTime.month, day=nowTime.day)
        next_task = Task.objects.filter_active(elevator=elevator_obj, day__gte=tt, status__in=(10, 20, 50, 100)).order_by("id").first()
        dic = {
            "deviceID": elevator_obj.register_code,
            "layerAmount": layer_amount,
            "stationAmount": station_amount,
            "OwnerID": str(elevator_obj.property_company.id),
            "OwnerName": elevator_obj.property_company.name,
            "OwnerTelephone": owner_telephone,
            "maintenanceID": str(elevator_obj.maintain_company.id) if elevator_obj.maintain_company else None,
            "maintenanceName": elevator_obj.maintain_company.name if elevator_obj.maintain_company else None,
            "maintenanceTelephone": maintenance_telephone,
            "streetName": u"梁溪区禾平之星旅馆",
            "installationPlace": elevator_obj.address,
            "elevatorCoordinates": [],
            "lastYearlyInspectionDate": None,
            "nextYearlyInspectionDate": nextYearlyInspectionDate,
            "elevatorName": elevator_obj.elevator_name,
            "deviceTypeName": elevator_type_name,
            "controlMode": None,
            "manufactorName": product_company_name,
            "manufactorDate": None,
            "checkUnitID": None,
            "checkUnitName": None,
            "safeValidDate": None,
            "insuredunit": None,
            "nextMaintenanceDate": str(next_task.day) if next_task else None,
            "96333num": elevator_obj.num
        }

        # 获取电梯坐标和地理位置
        t_qs = Task.objects.filter_active(elevator=elevator_obj.id).exclude(position=None)
        if t_qs.count() == 0:
            dic['elevatorCoordinates'].append(elevator_obj.lng)
            dic['elevatorCoordinates'].append(elevator_obj.lat)
            dic['streetName'] = u"梁溪区禾平之星旅馆"
            dic['installationPlace'] = elevator_obj.address

            # task_obj_qs = Task.objects.filter_active(elevator=elevator_obj.id, status=30)
            # if task_obj_qs.count():
            #     for task_obj in task_obj_qs:
            #         if task_obj.result:
            #             result_data = json.loads(task_obj.result)
            #             print result_data
            #             lng = result_data.get("lng")
            #             print lng
            #             lat = result_data.get("lat")
            #             print lat
            #             if lng and lat:
            #                 elevator_coordinates = str(lat) + ',' + str(lng)
            #                 dic['elevatorCoordinates'].append(lat)
            #                 dic['elevatorCoordinates'].append(lng)
            #                 items = {'location': elevator_coordinates, 'ak': 'C8eNlnlZ0qNHhx22eFU5aBWuiGhGCWI6', 'output': 'json'}
            #                 ret = requests.get('http://api.map.baidu.com/geocoder/v2/', params=items)
            #                 position_data = ret.json()
            #                 position_data = position_data.get("result")
            #                 street_name = position_data.get("formatted_address")
            #                 # dic['streetName'] = street_name
            #                 dic['streetName'] = u"梁溪区禾平之星旅馆"
            #                 dic['installationPlace'] = elevator_obj.address
            #
            #                 break
            #             else:
            #                 continue
            #         else:
            #             continue
            # else:
            #     pass
        else:
            t_obj = t_qs.last()
            coordinates = t_obj.position
            coordinates_lis = coordinates.split(",")
            elevator_coordinates = coordinates_lis[1] + "," + coordinates_lis[0]
            dic['elevatorCoordinates'] = coordinates_lis
            items = {'location': elevator_coordinates, 'ak': 'C8eNlnlZ0qNHhx22eFU5aBWuiGhGCWI6', 'output': 'json'}
            ret = requests.get('http://api.map.baidu.com/geocoder/v2/', params=items)
            position_data = ret.json()
            position_data = position_data.get("result")
            street_name = position_data.get("formatted_address")
            # dic['streetName'] = street_name
            # dic['streetName'] = elevator_obj.installation_place
            dic['streetName'] = u"梁溪区禾平之星旅馆"
            dic['installationPlace'] = elevator_obj.address

        data_list.append(dic)
        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100401",
            "gUID": g_uid,
            "dataList": data_list,
            "code": 0,
            "msg": "success"
        }
        logger.info("电梯运行信息log: ")
        logger.info(res)
        return JsonResponse(res)


# 根据电梯注册码获取电梯的运行信息
class QueryElevatorRunningInfo(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'gUID', 'deviceID']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        g_uid = data.get('gUID', None)
        code = data.get('deviceID', None)
        if not g_uid:
            res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
            return JsonResponse(res)
        if key != RESCUE_KEY or operation_command != "2100500" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        if not code:
            res['LinsData']['msg'] = u"电梯注册号缺失"
            return JsonResponse(res)
        elevator_status = ElevatorStatus.objects.filter_active(e=code).first()
        if not elevator_status:
            ac = AuthorityCode.objects.filter_active(elevator_code=code).first()
            if not ac:
                res['LinsData']['msg'] = u"电梯未找到"
                return JsonResponse(res)
            device_code_elevator = ac.device_code_elevator
            if not device_code_elevator:
                res['LinsData']['msg'] = u"电梯未找到"
                return JsonResponse(res)
            elevator_status = ElevatorStatus.objects.filter_active(o=device_code_elevator).order_by('-id').first()
            if not elevator_status:
                res['LinsData']['msg'] = u"电梯未找到"
                return JsonResponse(res)
        elevator_warning = ElevatorWarning.objects.filter_active(o=elevator_status.o).first()
        if elevator_status.u == "0" and elevator_status.d == "0":
            updown = 0
        elif elevator_status.u == "1" and elevator_status.d == "0":
            updown = 1
        elif elevator_status.u == "0" and elevator_status.d == "1":
            updown = 2
        else:
            updown = None

        o = elevator_status.o
        NumOfDailyRun = None  # 当天运行次数
        DailyRuntime = None  # 当天运行时间
        NumOfDailyDoorClose = None  # 当天关门次数
        NumOfAllRun = None  # 总计运行次数
        AllRuntime = None  # 总计运行时间
        NumOfAllDoorClose = None  # 总计关门次数

        ac = AuthorityCode.objects.filter_active(device_code_elevator=o).first()
        if ac:
            NumOfAllRun = ac.run_times
            NumOfDailyRun = ac.run_times - ac.yesterday_run_times
            NumOfAllDoorClose = ac.open_times
            NumOfDailyDoorClose = ac.open_times - ac.yesterday_open_times
            up_time = ac.up_time
            yesterday_up_time = ac.yesterday_up_time

            y = up_time / (3600 * 24 * 30 * 12)
            mo = up_time / (3600 * 24 * 30) % 12
            d = up_time / (3600 * 24) % 30
            h = up_time / 3600 % 24
            mi = up_time / 60 % 60
            s = up_time % 60
            AllRuntime = unicode(y) + u"年" + unicode(mo) + u"月" + unicode(d) + u"天" + unicode(h) + u"小时" + unicode(mi) + u"分" + unicode(s) + u"秒"
            dTime = up_time - yesterday_up_time
            hh = dTime / 3600 % 24
            mm = dTime / 60 % 60
            ss = dTime % 60
            DailyRuntime = unicode(hh) + u"小时" + unicode(mm) + u"分" + unicode(ss) + u"秒"
        # if elevator_status.od == "0" and elevator_status.om == "0" and elevator_status.sd == "1" and elevator_status.sm == "1":
        #     doorState = 0
        # elif elevator_status.od == "0" and elevator_status.om == "0" and elevator_status.sd == "1" and elevator_status.sm == "0":
        #     doorState = 1
        # elif elevator_status.od == "1" and elevator_status.om == "0" and elevator_status.sd == "0" and elevator_status.sm == "1":
        #     doorState = 2
        # elif elevator_status.od == "1" and elevator_status.om == "1" and elevator_status.sd == "0" and elevator_status.sm == "0":
        #     doorState = 3
        # else:
        #     doorState = None

        # if elevator_status.sm == "1":
        #     doorState = 0
        # elif elevator_status.sd == "1" and elevator_status.sm == "0" and elevator_status.od == "1" and elevator_status.om == "0":
        #     doorState = 1
        # elif elevator_status.sd == "0" and elevator_status.sm == "1" and elevator_status.od == "1" and elevator_status.om == "0":
        #     doorState = 2
        # elif elevator_status.u == "0" and elevator_status.d == "0" and elevator_status.om == "1":
        #     doorState = 3
        # else:
        #     doorState = None

        if elevator_status.ol in ("0", None, "") and elevator_status.fl in ("0", None, ""):
            ofState = 0
        elif elevator_status.fl == "1" and elevator_status.ol in ("0", None, ""):
            ofState = 1
        elif elevator_status.ol == "1":
            ofState = 2
        else:
            ofState = None

        if elevator_status.u == "0" and elevator_status.d == "0" and elevator_status.om == "0":
            doorState = 3
        else:
            doorState = 0

        alarms = {"1": u"轿厢报警按钮", "2": u"电梯困人", "3": u"非平层停梯", "4": u"安全回路断路", "5": u"轿厢冲顶",
                  "6": u"轿厢蹲底", "7": u"开门走梯", "8": u"电梯速度异常"}
        # , "9": u"电梯运行时安全回路断路", "10": u"关门故障",
        #           "11": u"开门故障", "12": u"轿厢在开锁区域外停止", "13": u"轿厢意外移动", "14": u"电动机运转时间限制器动作",
        #           "15": u"楼层位置丢失", "16": u"其他阻止电梯再启动的故障"
        if elevator_warning:
            alarmState = "e"
            if elevator_warning.a:
                alarm = ",".join([alarms[k] for k in elevator_warning.a.split(",") if k in alarms])
            else:
                alarm = ""
        else:
            alarmState = "c"
            alarm = ""

        # lm = elevator_status.lm
        # if lm == "0":
        #     mode = None
        # elif lm == "1":
        #     mode = "a"
        # elif lm == "2":
        #     mode = "m"
        # elif lm == "3":
        #     mode = "f"
        # elif lm == "4":
        #     mode = "f"
        # elif lm == "5":
        #     mode = "e"
        # else:
        #     mode = None

        now = datetime.datetime.now()
        dic = {
            "deviceID": code,
            "status": elevator_status.rs,
            "updown": updown,
            "mode": elevator_status.lm,
            "doorState": doorState,
            "ofState": ofState,
            "floor": elevator_status.cp,
            "alarmState": alarmState,
            "alarm": alarm,
            "dateTime": now.strftime("%Y-%m-%d %H:%M:%S"),
            "NumOfDailyRun": NumOfDailyRun,  # 当天运行次数
            "DailyRuntime": DailyRuntime,  # 当天运行时间
            "NumOfDailyDoorClose": NumOfDailyDoorClose,  # 当天关门次数
            "NumOfAllRun": NumOfAllRun,  # 总计运行次数
            "AllRuntime": AllRuntime,  # 总计运行时间
            "NumOfAllDoorClose": NumOfAllDoorClose,  # 总计关门次数
        }

        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "2100501",
            "gUID": g_uid,
            "dataList": [dic],
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 聆讯平台推送救援任务
class PushRescueMissionView(AuthenticationExceptView, WdAPIView):
    """
    聆讯平台推送救援任务
    """
    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'dataList']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        if key != RESCUE_KEY or operation_command != "1000000" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        data_list = data.get('dataList', None)
        if data_list:
            for rescue_data in data_list:
                print rescue_data
                elevator_code = rescue_data.get("deviceID", None)
                bill_id = rescue_data.get("billID", None)  # 救援任务单ID
                g_uid = rescue_data.get('gUID', None)
                rescuer_id = int(rescue_data.get('rescuerID', None))
                rescue_state = rescue_data.get('rescueState', None)
                if not elevator_code:
                    res['LinsData']['msg'] = u"电梯注册码为空，请检查"
                    return JsonResponse(res)
                if not bill_id:
                    res['LinsData']['msg'] = u"任务单号为空，请检查"
                    return JsonResponse(res)
                if not g_uid:
                    res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
                    return JsonResponse(res)
                if not rescuer_id:
                    res['LinsData']['msg'] = u"救援人员ID为空，请检查"
                    return JsonResponse(res)
                if not str(rescue_state):
                    res['LinsData']['msg'] = u"救援任务状态为空，请检查"
                    return JsonResponse(res)
                if rescue_state != 0:
                    res['LinsData']['msg'] = u"救援任务状态码不正确，请检查"
                    return JsonResponse(res)

                e_obj = ElevatorInfo.objects.filter_active(register_code=elevator_code).first()
                if not e_obj:
                    res['LinsData']['msg'] = u"需要救援的电梯不存在，请检查"
                    return JsonResponse(res)
                elevator_id = e_obj.id
                ep_qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=20, status=10)
                person_ids = [ep_obj.worker.id for ep_obj in ep_qs]
                rescuer_id = int(rescuer_id)
                # TODO
                # if rescuer_id not in person_ids:
                #     res['LinsData']['msg'] = u"该救援人员未绑定这部电梯，请检查"
                #     return JsonResponse(res)

                # 将任务信息存到数据库
                rescue_no = rescue_data.get("billID", None)

                elevator_code = rescue_data.get("deviceID", None)
                try:
                    elevator = ElevatorInfo.objects.filter_active(register_code=elevator_code).first()
                except Exception as e:
                    elevator = None

                g_uid = rescue_data.get("gUID", None)
                task_creator_id = rescue_data.get("creatorID", None)
                task_creator_name = rescue_data.get("creatorName", None)
                task_creator_phone = rescue_data.get("creatorPhone", None)

                task_create_time = rescue_data.get("createDatetime", None)
                task_create_time = datetime.datetime.strptime(task_create_time, "%Y-%m-%d %H:%M:%S")

                task_depict = rescue_data.get("taskDepict", None)
                rescue_depict = rescue_data.get("rescueDepict", None)
                # rescue_state = rescue_data.get("rescueState", None)

                maintain_company_id = int(rescue_data.get("maintenanceID", None))
                try:
                    maintain_company = CompanyInfo.objects.filter_active(id=maintain_company_id).first()
                except Exception as e:
                    maintain_company = None

                coordinate_system = rescue_data.get("coordinateSystem", None)

                rescuer_id = int(rescue_data.get("rescuerID", None))
                try:
                    rescuer = Person.objects.filter_active(id=rescuer_id).first()
                except Exception as e:
                    rescuer = None
                rescuer_name = rescue_data.get("rescuerName", None)
                rescuer_phone = rescue_data.get("rescuerPhone", None)
                rescuer_coordinates = rescue_data.get("rescuerCoordinates", None)
                rescuer_coordinates = json.dumps(rescuer_coordinates)
                rescuer_state = rescue_data.get("rescuerState", None)

                # property_company_id = int(rescue_data.get("subDistrictID", None))
                # try:
                #     property_company = CompanyInfo.objects.filter_active(id=property_company_id).first()
                # except Exception as e:
                #     property_company = None

                property_company_name = rescue_data.get("subDistrictName", None)
                property_company_phone = rescue_data.get("subDistrictPhone", None)
                terminal_name = rescue_data.get("terminalName", None)
                warn_bill_no = rescue_data.get("warnBillID", None)
                warn_bill_coordinates = rescue_data.get("warnCoordinates", None)
                warn_bill_coordinates = json.dumps(warn_bill_coordinates)

                warn_bill_time = rescue_data.get("warnDateTime", None)
                warn_bill_time = datetime.datetime.strptime(warn_bill_time, "%Y-%m-%d %H:%M:%S")

                remark = rescue_data.get("remark", None)

                try:
                    RescueTask.objects.create(rescue_no=rescue_no, elevator=elevator, g_uid=g_uid,
                                              task_creator_id=task_creator_id, task_creator_name=task_creator_name,
                                              task_creator_phone=task_creator_phone, task_depict=task_depict,
                                              rescue_depict=rescue_depict, rescue_state=0,
                                              maintain_company=maintain_company, coordinate_system=coordinate_system,
                                              rescuer=rescuer, rescuer_name=rescuer_name, rescuer_phone=rescuer_phone,
                                              rescuer_coordinates=rescuer_coordinates, rescuer_state=rescuer_state,
                                              property_company_name=property_company_name,
                                              property_company_phone=property_company_phone,
                                              terminal_name=terminal_name, warn_bill_no=warn_bill_no,
                                              warn_bill_coordinates=warn_bill_coordinates,
                                              warn_bill_time=warn_bill_time, remark=remark,
                                              task_create_time=task_create_time, elevator_code=elevator_code)
                    push_by_alias.delay(str(rescuer.id), u"已收到紧急救援任务，请及时处理")
                except Exception as e:
                    logger.info(e)
                    res['LinsData']['msg'] = u"发生错误"
                    return JsonResponse(res)

            res['LinsData'] = {
                "key": key,
                "dataType": RESCUE_DATA_TYPE,
                "operationCommand": "1000001",
                "code": 0,
                "msg": "success"
            }
            return JsonResponse(res)
        else:
            res['LinsData']['msg'] = u"任务列表为空，请检查"
            return JsonResponse(res)


# 维保人员接收到救援任务
class ReceiveMissionView(AuthenticationExceptView, WdAPIView):
    """
    维保人员接收到救援任务
    """
    def post(self, request, *args, **kwargs):
        ret = {
            "code": -1,
            "status": False,
            "message": u""
        }
        data = {
            "LinsData": None
        }

        lins_data = {
            "key": RESCUE_KEY,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1100100",
            "dataList": []
        }
        task_id = self.request.data.get("task_id", None)
        data_dic = dict()
        task_obj = RescueTask.objects.filter_active(id=int(task_id)).first()
        bill_id = task_obj.rescue_no
        g_uid = task_obj.g_uid
        rescuer_id = task_obj.rescuer.id
        rescuer_receive_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        rescuer_state = 1

        data_dic["billID"] = bill_id
        data_dic["gUID"] = g_uid
        data_dic["rescuerID"] = str(rescuer_id)
        data_dic["rescuerState"] = rescuer_state
        data_dic["rescuerReceiveDateTime"] = rescuer_receive_time

        lins_data["dataList"].append(data_dic)
        data['LinsData'] = lins_data
        try:
            res = requests.post(RESCUE_INFO['RECEIVE_MISSION'], json=data)
            logger.info(data)
        except Exception as e:
            print e
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        if res.status_code == 200:
            receive_data = res.json()
            logger.info(receive_data)
            print receive_data
            if receive_data['LinsData']['operationCommand'] == "1100101" and receive_data['LinsData']['code'] == '0' \
                    and receive_data['LinsData']['msg'] == "success":
                ret = {
                    "code": 0,
                    "status": True,
                    "message": "success"
                }
                task_obj.rescuer_state = 1
                task_obj.rescuer_receive_time = datetime.datetime.strptime(rescuer_receive_time,
                                                                           "%Y-%m-%d %H:%M:%S")
                task_obj.rescue_state = 10
                task_obj.save()
                r = RescueTaskRetrieveSerializer(instance=task_obj, many=False).data
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, r)
            else:
                ret = {
                    "code": -1,
                    "status": False,
                    "message": u"维保人员接受任务失败"
                }
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        else:
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)


# 维保人员确认接收到救援任务
class ComfirmMissonView(AuthenticationExceptView, WdAPIView):
    """
    维保人员确认接收到救援任务
    """
    def post(self, request, *args, **kwargs):
        ret = {
            "code": -1,
            "status": False,
            "message": u""
        }
        data = {
            "LinsData": None
        }
        lins_data = {
            "key": RESCUE_KEY,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1100200",
            "dataList": []
        }
        task_id = self.request.data.get("task_id", None)
        data_dic = dict()
        task_obj = RescueTask.objects.filter_active(id=task_id).first()
        bill_id = task_obj.rescue_no
        g_uid = task_obj.g_uid
        rescuer_id = task_obj.rescuer.id
        rescuer_confirm_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        rescuer_state = 2

        data_dic["billID"] = bill_id
        data_dic["gUID"] = g_uid
        data_dic["rescuerID"] = str(rescuer_id)
        data_dic["rescuerState"] = rescuer_state
        data_dic["rescuerConfirmDateTime"] = rescuer_confirm_time

        lins_data["dataList"].append(data_dic)
        data['LinsData'] = lins_data
        try:
            res = requests.post(RESCUE_INFO['COMFIRM_MISSION'], json=data)
        except Exception as e:
            print e
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        if res.status_code == 200:
            receive_data = res.json()
            if receive_data['LinsData']['operationCommand'] == "1100201" and receive_data['LinsData']['code'] == '0' and \
                    receive_data['LinsData']['msg'] == "success":
                # ret = {
                #     "code": 0,
                #     "status": True,
                #     "message": "success"
                # }
                task_obj.rescuer_state = 2
                task_obj.rescuer_confirm_time = datetime.datetime.strptime(rescuer_confirm_time,
                                                                           "%Y-%m-%d %H:%M:%S")
                task_obj.rescue_state = 20
                task_obj.save()
                r = RescueTaskRetrieveSerializer(instance=task_obj, many=False).data
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, r)
            else:
                ret = {
                    "code": -1,
                    "status": False,
                    "message": u"维保人员确认任务失败"
                }
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        else:
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)


# 维保人员拒绝救援任务
class RefuseMissionView(AuthenticationExceptView, WdAPIView):
    """
    维保人员拒绝救援任务
    """
    def post(self, request, *args, **kwargs):
        ret = {
            "code": -1,
            "status": False,
            "message": u""
        }
        data = {
            "LinsData": None
        }
        lins_data = {
            "key": RESCUE_KEY,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1100300",
            "dataList": []
        }
        task_id = self.request.data.get("task_id", None)
        confirm_media = self.request.data.get("confirm_media", None)
        refuse_reason = self.request.data.get('refuse_reason', None)
        data_dic = dict()
        rescue = []
        task_obj = RescueTask.objects.filter_active(id=task_id).first()
        bill_id = task_obj.rescue_no
        g_uid = task_obj.g_uid
        rescuer_id = task_obj.rescuer.id
        rescuer_state = 5
        # refuse_reason = task_obj.refuse_reason
        task_obj.refuse_reason = refuse_reason
        task_obj.save()
        confirm_create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        confirm_media_data = confirm_media.split(",")
        logger.info("原始文件")
        logger.info(confirm_media_data)

        for item in confirm_media_data:
            rescue_dic = dict()
            rescue_dic['gUID'] = "".join(random.sample(string.uppercase + string.hexdigits, 20))
            rescue_dic['resourceType'] = 1
            rescue_dic['createDatetime'] = confirm_create_time
            rescue_dic['fileID'] = 'ZYSP' + str(int(time.time()*1000000))
            name = re.search(r'.*uploaded/(.*)', item)
            file_name = name.group(1)
            rescue_dic['fileName'] = file_name
            if "jpg" in item:
                rescue_dic['fileType'] = 1
            elif "mp4" in item:
                rescue_dic['fileType'] = 2
            rescue_dic['fileUrl'] = item
            rescue.append(rescue_dic)

        data_dic["billID"] = bill_id
        data_dic["gUID"] = g_uid
        data_dic["rescuerID"] = str(rescuer_id)
        data_dic["rescuerState"] = rescuer_state
        data_dic["refuseReason"] = refuse_reason
        data_dic["rescuerState"] = rescuer_state
        data_dic["rescue"] = rescue

        lins_data["dataList"].append(data_dic)
        data['LinsData'] = lins_data
        try:
            res = requests.post(RESCUE_INFO['REFUSE_MISSION'], json=data)
            logger.info("维保拒绝data")
            logger.info(data)
        except Exception as e:
            print e
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        if res.status_code == 200:
            receive_data = res.json()
            if receive_data['LinsData']['operationCommand'] == "1100301" and receive_data['LinsData']['code'] == '0' and \
                    receive_data['LinsData']['msg'] == "success":
                ret = {
                    "code": 0,
                    "status": True,
                    "message": u"拒绝任务提交成功"
                }
                task_obj.rescuer_state = 5
                task_obj.rescue_state = 50
                task_obj.rescuer_refuse_time = datetime.datetime.strptime(confirm_create_time,
                                                                          "%Y-%m-%d %H:%M:%S")
                task_obj.confirm_media = confirm_media
                task_obj.save()
                r = RescueTaskRetrieveSerializer(instance=task_obj, many=False).data
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, r)
            elif receive_data['LinsData']['operationCommand'] == "1100302" and receive_data['LinsData']['code'] == '0' and \
                    receive_data['LinsData']['msg'] == "success":
                ret = {
                    "code": 1,
                    "status": True,
                    "message": u"拒绝任务提交失败"
                }
                task_obj.rescue_state = 60
                task_obj.save()
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
            else:
                ret = {
                    "code": -1,
                    "status": False,
                    "message": u"维保人员拒绝任务提交失败"
                }
                task_obj.rescue_state = 60
                task_obj.save()
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        else:
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)


# 坐席人员审核拒绝任务结果
class CheckRefuseMissionView(AuthenticationExceptView, WdAPIView):
    """
    坐席人员审核拒绝任务结果
    """

    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'dataList']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        data_list = data.get('dataList', None)
        if key != RESCUE_KEY or operation_command != "1000400" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        if not data_list:
            res['LinsData']['msg'] = u"任务列表为空，请检查"
            return JsonResponse(res)
        data_lis = data['dataList']
        for item in data_lis:
            rescue_no = item['billID']
            rescuer_state = item['RescuerState']
            task_obj = RescueTask.objects.filter_active(rescue_no=rescue_no).first()
            if rescuer_state == 6:
                reject_reason = item['rejectReason']
                task_obj.rescuer_state = 6
                task_obj.rescue_state = 40
                task_obj.reject_reason = reject_reason
                task_obj.save()
            elif rescuer_state == 7:
                reject_reason = item['rejectReason']
                task_obj.rescuer_state = 7
                task_obj.rescue_state = 70
                task_obj.reject_reason = reject_reason
                task_obj.save()

        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1000401",
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 维保人员到达现场
class ArrivePositionView(AuthenticationExceptView, WdAPIView):
    """
    维保人员到达现场
    """
    def post(self, request, *args, **kwargs):
        ret = {
            "code": -1,
            "status": False,
            "message": u""
        }
        data = {
            "LinsData": None
        }
        lins_data = {
            "key": RESCUE_KEY,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1100500",
            "dataList": []
        }
        task_id = self.request.data.get("task_id", None)
        data_dic = dict()
        task_obj = RescueTask.objects.filter_active(id=task_id).first()
        bill_id = task_obj.rescue_no
        g_uid = task_obj.g_uid
        rescuer_id = task_obj.rescuer.id
        rescuer_arrive_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        rescuer_state = 3

        data_dic["billID"] = bill_id
        data_dic["gUID"] = g_uid
        data_dic["rescuerID"] = str(rescuer_id)
        data_dic["rescuerState"] = rescuer_state
        data_dic["rescuerArriveDateTime"] = rescuer_arrive_time

        lins_data["dataList"].append(data_dic)
        data['LinsData'] = lins_data
        try:
            res = requests.post(RESCUE_INFO['ARRIVE_RESCUE'], json=data)
        except Exception as e:
            print e
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        if res.status_code == 200:
            receive_data = res.json()
            if receive_data['LinsData']['operationCommand'] == "1100501" and receive_data['LinsData']['code'] == '0' and \
                    receive_data['LinsData']['msg'] == "success":
                ret = {
                    "code": 0,
                    "status": True,
                    "message": "success"
                }
                task_obj.rescuer_state = 3
                task_obj.rescue_state = 30
                task_obj.rescuer_arrive_time = datetime.datetime.strptime(rescuer_arrive_time,
                                                                          "%Y-%m-%d %H:%M:%S")
                task_obj.save()
                r = RescueTaskRetrieveSerializer(instance=task_obj, many=False).data
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, r)
            else:
                ret = {
                    "code": -1,
                    "status": False,
                    "message": u"维保人员到达现场确认失败"
                }
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        else:
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)


# 维保人员完成救援任务
class EndMissionView(AuthenticationExceptView, WdAPIView):
    """
    维保人员完成救援任务
    """
    def post(self, request, *args, **kwargs):
        ret = {
            "code": -1,
            "status": False,
            "message": u""
        }
        data = {
            "LinsData": None
        }
        lins_data = {
            "key": RESCUE_KEY,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1100600",
            "dataList": []
        }
        task_id = self.request.data.get("task_id", None)
        rescue_depict = self.request.data.get('rescue_depict', None)
        data_dic = dict()
        task_obj = RescueTask.objects.filter_active(id=task_id).first()
        bill_id = task_obj.rescue_no
        g_uid = task_obj.g_uid
        rescuer_id = task_obj.rescuer.id
        rescuer_end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        rescuer_state = 4

        data_dic["billID"] = bill_id
        data_dic["gUID"] = g_uid
        data_dic["rescuerID"] = str(rescuer_id)
        data_dic["rescuerState"] = rescuer_state
        data_dic["rescuerEndDateTime"] = rescuer_end_time

        lins_data["dataList"].append(data_dic)
        data['LinsData'] = lins_data
        try:
            res = requests.post(RESCUE_INFO['END_MISSION'], json=data)
        except Exception as e:
            print e
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        if res.status_code == 200:
            receive_data = res.json()
            if receive_data['LinsData']['operationCommand'] == "1100601" and receive_data['LinsData']['code'] == '0' and \
                    receive_data['LinsData']['msg'] == "success":
                ret = {
                    "code": 0,
                    "status": True,
                    "message": "success"
                }
                task_obj.rescuer_state = 4
                task_obj.rescue_depict = rescue_depict
                task_obj.rescuer_end_time = datetime.datetime.strptime(rescuer_end_time,
                                                                       "%Y-%m-%d %H:%M:%S")
                task_obj.rescue_state = 100
                task_obj.save()
                r = RescueTaskRetrieveSerializer(instance=task_obj, many=False).data
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, r)
            else:
                ret = {
                    "code": -1,
                    "status": False,
                    "message": u"维保人员完成救援任务确认失败"
                }
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        else:
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)


# 发送误报信息
class SendMisinformationView(AuthenticationExceptView, WdAPIView):
    """
    发送误报信息
    """
    def post(self, request, *args, **kwargs):
        res = {
            "LinsData": {
                "code": -1,
                "msg": u""
            }
        }
        data = self.request.data.get('LinsData', None)
        if not data:
            res['LinsData']['msg'] = u"参数错误:未传参"
            return JsonResponse(res)
        try:
            keys = data.keys()
        except Exception as e:
            logger.info(e)
            res['LinsData']['msg'] = u"参数类型有误"
            return JsonResponse(res)
        key_format = ['key', 'dataType', 'operationCommand', 'dataList']
        if sorted(keys) != sorted(key_format):
            res['LinsData']['msg'] = u"参数错误:键值对不对"
            return JsonResponse(res)
        key = data.get('key', None)
        data_type = data.get('dataType', None)
        operation_command = data.get('operationCommand', None)
        data_list = data.get('dataList', None)
        if key != RESCUE_KEY or operation_command != "1000700" or data_type != RESCUE_DATA_TYPE:
            res['LinsData']['msg'] = u"请检查参数:值有误"
            return JsonResponse(res)
        if not data_list:
            res['LinsData']['msg'] = u"误报信息任务列表为空"
            return JsonResponse(res)
        for rescue_data in data_list:
            bill_id = rescue_data.get("billID", None)  # 救援任务单ID
            g_uid = rescue_data.get('gUID', None)
            rescuer_id = rescue_data.get('rescuerID', None)
            rescue_depict = rescue_data.get('rescueDepict', None)
            rescue_state = rescue_data.get('rescueState', None)
            if not bill_id:
                res['LinsData']['msg'] = u"任务单号为空，请检查"
                return JsonResponse(res)
            if not g_uid:
                res['LinsData']['msg'] = u"请传入一个唯一序号以便于您进行区分"
                return JsonResponse(res)
            if not rescuer_id:
                res['LinsData']['msg'] = u"救援人员ID为空，请检查"
                return JsonResponse(res)
            if not rescue_depict:
                res['LinsData']['msg'] = u"救援任务误报信息内容为空，请检查"
                return JsonResponse(res)
            if not rescue_state:
                res['LinsData']['msg'] = u"救援任务状态为空，请检查"
                return JsonResponse(res)
            if rescue_state != 2:
                res['LinsData']['msg'] = u"救援任务状态码不正确，请检查"
                return JsonResponse(res)
            task_obj = RescueTask.objects.filter_active(rescue_no=bill_id).first()
            task_obj.rescue_state = 80
            task_obj.rescue_depict = rescue_depict
            task_obj.save()
        res['LinsData'] = {
            "key": key,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1000701",
            "code": 0,
            "msg": "success"
        }
        return JsonResponse(res)


# 维保人员确认误报信息
class ComfirmMisinformationView(AuthenticationExceptView, WdAPIView):
    """
    维保人员确认误报信息
    """
    def post(self, request, *args, **kwargs):
        ret = {
            "code": -1,
            "status": False,
            "message": u""
        }
        data = {
            "LinsData": None
        }
        lins_data = {
            "key": RESCUE_KEY,
            "dataType": RESCUE_DATA_TYPE,
            "operationCommand": "1100800",
            "dataList": []
        }
        task_id = self.request.data.get("task_id", None)
        data_dic = dict()
        task_obj = RescueTask.objects.filter_active(id=task_id).first()
        bill_id = task_obj.rescue_no
        g_uid = task_obj.g_uid
        rescuer_id = task_obj.rescuer.id
        rescuer_end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        rescuer_state = 8

        data_dic["billID"] = bill_id
        data_dic["gUID"] = g_uid
        data_dic["rescuerID"] = str(rescuer_id)
        data_dic["rescuerState"] = rescuer_state
        data_dic["rescuerEndDateTime"] = rescuer_end_time

        lins_data["dataList"].append(data_dic)
        data['LinsData'] = lins_data
        try:
            res = requests.post(RESCUE_INFO['MISINFORMATION'], json=data)
        except Exception as e:
            print e
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        if res.status_code == 200:
            receive_data = res.json()
            if receive_data['LinsData']['operationCommand'] == "1100801" and receive_data['LinsData']['code'] == '0' and \
                    receive_data['LinsData']['msg'] == "success":
                ret = {
                    "code": 0,
                    "status": True,
                    "message": "success"
                }
                task_obj.rescuer_state = 8
                task_obj.rescuer_end_time = datetime.datetime.strptime(rescuer_end_time,
                                                                       "%Y-%m-%d %H:%M:%S")
                task_obj.rescue_state = 90
                task_obj.save()
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, ret)
            else:
                ret = {
                    "code": -1,
                    "status": False,
                    "message": u"维保人员误报信息确认失败"
                }
                return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)
        else:
            ret["message"] = u"服务器通讯失败，POST请求异常"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, ret)


# 救援任务列表
class RescueTaskListView(WdListAPIView):
    model = RescueTask
    serializer_class = RescueTaskListSerializer
    QUERY_WITH_ACTIVE = True

    # def get_serializer_class(self, *args, **kwargs):
    #     if self.request.method.lower() == "get":
    #         return self.g_serializer_class

    # def get_queryset(self):
    #     qs = self.model.objects.all()
    #     if self.QUERY_WITH_ACTIVE:
    #         qs = qs.filter(is_active=True)
    #     user = self.request.user
    #     person_obj = Person.objects.filter_active(auth_user=user.id).first()
    #     qs = qs.filter(rescuer=person_obj.id).order_by('-id')
    #     return qs

    def qs_filter(self, qs):
        qs = super(RescueTaskListView, self).qs_filter(qs)
        user = self.request.user
        if user.role == 10:
            person = user.person
            qs = qs.filter(rescuer=person)
        elif user.role == 30:
            company = user.company_person.company
            qs = qs.filter(property_company=company)
        else:
            qs = qs.none()
        return qs

    def qs_business_role(self, qs):
        return qs


# 救援任务检索 更新
class RescueTaskRetrieveUpdateView(WdRetrieveUpdateAPIView):
    model = RescueTask
    POST_DATA_RESPONSE = True
    p_serializer_class = RescueTaskSerializer
    g_serializer_class = RescueTaskRetrieveSerializer

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class


# 获取代办的任务单数
class WaitRescueTaskNumView(WdListAPIView):

    def get(self, request, *args, **kwargs):
        wait_task_data = {
            "wait_task_num": None
        }
        rescuer_id = self.request.GET.get("rescuer_id")
        states = [10, 70]
        rt_qs = RescueTask.objects.filter_active(rescuer=rescuer_id, rescue_state__in=states)
        wait_task_num = rt_qs.count()
        wait_task_data['wait_task_num'] = wait_task_num
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, wait_task_data)


class InitRescueTaskView(WdListAPIView):

    def get(self, request, *args, **kwargs):
        now = datetime.datetime.now()
        today = datetime.datetime(year=now.year, month=now.month, day=now.day)
        user = self.request.user
        if user.role == 10:
            person = self.request.user.person
            rt_qs = RescueTask.objects.filter_active(rescuer=person, rescue_state=0, task_create_time__gte=today).order_by('-id').first()
        elif user.role == 30:
            company = user.company_person.company
            rt_qs = RescueTask.objects.filter_active(property_company=company, rescue_state=0,
                                                     task_create_time__gte=today).order_by('-id').first()
        else:
            rt_qs = []
        if rt_qs:
            data = RescueTaskRetrieveSerializer(instance=rt_qs, many=False).data
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)
        return general_json_response(status.HTTP_200_OK, ErrorCode.ELEVATOR_NOT_EXIST)

















